<template>
  <div class="dropdown" ref="dropdownRef">
    <div class="dropdown-trigger" @click="toggleDropdown">
      <button class="btn btn-danger dropdown-toggle" aria-haspopup="true" aria-controls="dropdown-menu3">
        <span>查看更多</span>
      </button>
    </div>
    <div class="dropdown-menu" id="dropdown-menu3" style="display: block" v-if="isOpen" role="menu">
      <div class="dropdown-content">
        <slot></slot>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, watch } from 'vue';
import useClickOutside from '@/hooks/useClickOutside';
export default defineComponent({
  name: 'dropdown',
  setup() {
    const isOpen = ref<boolean>(false);
    const dropdownRef = ref<HTMLElement | null>(null);
    const toggleDropdown = () => {
      isOpen.value = !isOpen.value;
    };
    /* const handler = (e: MouseEvent) => {
      if (dropdownRef.value) {
        // 判断点击的节点是否在下拉框内，不在下拉框内并且isOpen是true [tag]
        if (!dropdownRef.value.contains(e.target as HTMLElement) && isOpen.value) {
          isOpen.value = false
        }
      }
    }
    onMounted(() => {
      document.addEventListener('click', handler)
    })
    onUnmounted(() => {
      document.removeEventListener('click', handler)
    }) */
    // use hooks
    const clickOutside = useClickOutside(dropdownRef);
    watch(clickOutside, () => {
      if (clickOutside.value && isOpen.value) {
        isOpen.value = false;
      }
    });
    return { isOpen, toggleDropdown, dropdownRef };
  }
});
</script>

<style lang="less" scoped>
.dropdown {
  display: inline-block;
  margin-left: 10px;
}
</style>
